/***********************************
 * NotificationGenerator class - notifications are awesome
 * This class listens for incoming sms, if it sees one, 
 * it generates a notification iff the user has notifications enabled
 * additionally, it will allow them to use the 
 * notification ringtone referenced in the preferences
 */
package edu.csuohio.mad.ssmk.subtxt;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsMessage;

public class NotificationGenerator extends BroadcastReceiver {

	private SharedPreferences asp;
	private boolean notifyUser;
	private String notifyTone;
	private NotificationManager notman;
	private Notification not;
	private ContactSupport cs;

	@Override
	public void onReceive(Context context, Intent intent) {
		asp = PreferenceManager.getDefaultSharedPreferences(context);
		notifyUser = asp.getBoolean("gen_notify", true);
		notifyTone = asp.getString("notification", "");

		// if notifications are enabled
		if (notifyUser) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				// parse the incoming sms message objects
				Object[] pdus = (Object[]) bundle.get("pdus");
				SmsMessage[] msgs = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++)
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				// generate a notification for each message
				for (SmsMessage msg : msgs) {
					cs = ContactSupport.getInstance(context);
					createNB(context,
							cs.getDisplayName(msg.getOriginatingAddress()));
				}
			}
		}
	}

	@SuppressWarnings("deprecation")
	// generate notification using the sender's display name
	private void createNB(Context context, String sender) {
		String ns = Context.NOTIFICATION_SERVICE;
		notman = (NotificationManager) context.getSystemService(ns);

		// use the application image
		int icon = R.drawable.ic_launcher;
		CharSequence contentTitle = "SubTxt";
		CharSequence tickerText = "Message from: " + sender;
		long when = System.currentTimeMillis();
		not = new Notification(icon, tickerText, when);
		// have the notification bring up subtxt directly if the user clicks on
		// a notification message
		Intent notificationIntent = new Intent(context, SubTxt.class);

		PendingIntent msgIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		not.flags |= Notification.FLAG_AUTO_CANCEL;
		// if notification sounds are enabled, select our sound
		if (!notifyTone.contentEquals(""))
			not.sound = Uri.parse(notifyTone);
		// generate the notification
		not.setLatestEventInfo(context, contentTitle, tickerText, msgIntent);
		notman.notify(0, not);
	}
}